package 打牢基础30天.day02.my;

/**
 * @Author yaya
 * @Create 2024/6/4 20:27
 * Description:计算小和
 */
public class Code02_SmallSum {

    public static int smallSum(int[] arr) {
        if (arr == null || arr.length < 2) return 0 ;
        return smallSum(arr, 0, arr.length - 1);
    }

    private static int smallSum(int[] arr, int left, int right) {
        if (left == right) return 0;
        int mid = left + ((right - left) >> 1);

        return smallSum(arr, left, mid) +
                smallSum(arr, mid + 1, right) +
                merge(arr, mid, left, right);
    }

    private static int merge(int[] arr, int mid, int left, int right) {
        int i = 0;
        int[] help = new int[right - left + 1];
        int p1 = left;
        int p2 = mid + 1;
        int result = 0;

        while (p1 <= mid && p2 <= right) {
            result += arr[p1] < arr[p2] ? (right - p2 + 1) * arr[p1] : 0;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }

        while (p1 <= mid){
            help[i++] = arr[p1++];
        }

        while (p2 <= right){
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[left + i] = help[i];
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(smallSum(new int[]{1,4,2,3,5}));
    }


}
